package cn.tom.service;

import cn.tom.entity.Type;
import cn.tom.dao.TypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookTypeServiceImpl implements BookTypeService {

    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Type findById(int id) {
        return this.typeMapper.findById(id);
    }

    @Override
    public List<Type> findAll() {
        return this.typeMapper.findAll();
    }

    @Override
    public List<Type> findAll2() {
        System.out.println("findALL2===============");
        // 尝试从 Redis 中获取缓存的书籍类型数据
        List<Type> cachedBookTypes = redisTemplate.opsForList().range("findTypeAll2", 0, -1);
        if (cachedBookTypes != null && !cachedBookTypes.isEmpty()) {
            System.out.println("redis有数据直接取===========");
            // 如果 Redis 中有缓存数据，则直接返回缓存的数据
            return cachedBookTypes;
        } else {
            // 如果 Redis 中没有缓存数据，则从数据库中获取数据
            List<Type> findAll2 = this.typeMapper.findAll2();
            // 将数据缓存到 Redis 中
            System.out.println("redis存数据=============");
            //redisTemplate.opsForList().rightPushAll("findAll2", findAll2.toArray(new Type[0]));
            redisTemplate.opsForList().rightPushAll("findTypeAll2", findAll2);//配置序列化就可以不用.toArray(new Type[0])
            return findAll2;
        }
    }

    @Override
    public void remove(int id) {
        redisTemplate.delete("findTypeAll2");
        this.typeMapper.remove(id);
        redisTemplate.delete("findTypeAll2");
    }

    @Override
    public void update(int id, String name, int pid, int prio) {
        redisTemplate.delete("findTypeAll2");
        this.typeMapper.update(id, name, pid, prio);
        redisTemplate.delete("findTypeAll2");
    }

    @Override
    public void add(String name, int pid, int prio) {

        Type type = new Type();
        type.setName(name);
        type.setPid(pid);
        type.setPrio(prio);
        redisTemplate.delete("findTypeAll2");
        this.typeMapper.add(type);
        /*redisTemplate.opsForList().rightPushAll("findTypeAll2", type);*/
        redisTemplate.delete("findTypeAll2");
    }
}
